<?php

namespace app\admin\controller\sys;

use app\admin\controller\sys\model\AdminUser;
use app\auto\lib\FileAutoLib;
use app\auto\model\TableAuto;
use app\auto\model\TableFieldAuto;
use app\auto\model\TableRelationsAuto;
use app\auto\service\TableAutoService;
use app\auto\service\TableFieldAutoService;
use app\auto\service\TableRelationsAutoService;
use app\BaseController;
use app\admin\service\AdminLog as AdminLogService;
use think\App;
use think\facade\Db;
use think\facade\View;

/**
 * 后台日志
 * Class AdminLog
 * @package app\admin\controller\sys
 */
class AdminLog extends BaseController
{
    public $service;
    public $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->service = new AdminLogService();
        $this->model = new \app\admin\controller\sys\model\AdminLog();
    }


    /**
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $where = [];
        $start_time = input('start_time', '');
        $start_time = $start_time ? strtotime($start_time) : 0;
        $end_time = input('end_time', '');
        $end_time = $end_time ? strtotime($end_time) + 60 * 60 * 24 - 1 : time() + time();
        $where[] = ['create_time', 'between', [$start_time, $end_time]];
        $table_name = input('table_name', '');
        if ($table_name) {
            $where[] = ['table_name', '=', $table_name];
            $table_auto_id = TableAuto::where('name', $table_name)->value('id');
            $field_name_arr = (new TableFieldAutoService())->getList(['table_auto_id'=>$table_auto_id])->toArray();
            View::assign('field', $field_name_arr);
        } else {
            View::assign('field', []);
        }
        $user_id = input('user_id', 0, 'trim');
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }
        $field_name = input('field_name', '');
        if ($field_name) {
            $where[] = ['field_name', 'like', '%|'.$field_name.'|%'];
        }
        $type = input('type', 0);
        if ($type) {
            $where[] = ['type', '=', $type];
        }
        $pk_id = input('pk_id', 0);
        if ($pk_id) {
            $where[] = ['pk_id', '=', $pk_id];
        }
        View::assign($this->service->getRelationsListPaginate($where, [], 'id asc'));
        $table_auto_arr = (new TableAutoService())->getList([])->toArray();
        View::assign('auto', $table_auto_arr);
        try {
            $user_arr = AdminUser::select();
        } catch (\Exception $exception) {
            $user_arr = [];
        }
        View::assign('user_arr', $user_arr);
        return View::fetch();
    }

    public function test()
    {
        $file_name = "../app/common/base/model/BaseModel.php";
        $content = file_get_contents($file_name);
        if (strpos($content, 'delete_time_soft') !== false) {
            $data = $this->service->getRelationsList([]);
            $content = str_replace("delete_time_soft", "delete_time", $content);
            file_put_contents($file_name, $content);
            return json($data);
        } else {
            $content = str_replace("delete_time", "delete_time_soft", $content);
            file_put_contents($file_name, $content);
            $this->redirect(url('test'), 0);
        }
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = input('id', 0);
        $log_data = $this->service->getById($id);
        $table_auto_id = TableAuto::where('name', $log_data['table_name'])->value('id');
        $base = new FileAutoLib('', $table_auto_id);
        $this_service = '\app\common\service\\' . $base->class_name . 'Service';
        $file_name = "../app/common/base/model/BaseModel.php";
        $content = file_get_contents($file_name);
        if (strpos($content, 'delete_time_soft') !== false) {
            $content = str_replace("delete_time_soft", "delete_time", $content);
            file_put_contents($file_name, $content);
            $data = (new $this_service())->getDeleteFullById($log_data['pk_id']);
            if ($data) {
                $data = $data->toArray();
            }
            $where_relation = [];
            $where_relation[] = ['table_auto_id', '=', $table_auto_id];
            $where_relation[] = ['is_delete', '=', 1];
            $relations_arr = (new TableRelationsAutoService())->getRelationsList($where_relation)->toArray();
            $log_where = [];
            $log_where[] = [
                'id' => $id,
                'table_name' => $base->table_name
            ];
            foreach ($relations_arr as $k=>$v) {
                $item_data = [];
                $pids = $v['pids'];
                if ($pids) {
                    $route_arr = explode(',', trim($pids . ',' . $v['id'], ','));
                } else {
                    $route_arr = [$v['id']];
                }
                $ids = $this->getIds($data, $route_arr);
                if ($ids) {
                    $log_where[] = [
                        ['pk_id', 'in', $ids],
                        ['table_name', '=', $v['bindTableAuto']['name']]
                    ];
                }
            }
            $res = [];
            foreach ($log_where as $v) {
                $data = $this->service->getRelationsList($v)->toArray();
                $res = array_merge($res, $data);
            }

            array_multisort(array_column($res, 'id'), SORT_ASC, $res);


            $data = input();
            $where = [];
            $start_time = input('start_time', '');
            $start_time = $start_time ? strtotime($start_time) : 0;
            $end_time = input('end_time', '');
            $end_time = $end_time ? strtotime($end_time) + 60 * 60 * 24 - 1 : time() + time();
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
            $table_name = input('table_name1', '');
            if ($table_name) {
                $where[] = ['table_name', '=', $table_name];
                $table_auto_id = TableAuto::where('name', $table_name)->value('id');
                $field_name_arr = (new TableFieldAutoService())->getList(['table_auto_id'=>$table_auto_id])->toArray();
                View::assign('field', $field_name_arr);
            } else {
                View::assign('field', []);
            }
            $user_id = input('user_id', 0, 'trim');
            if ($user_id) {
                $where[] = ['user_id', '=', $user_id];
            }
            $field_name = input('field_name', '');
            if ($field_name) {
                $where[] = ['field_name', 'like', '%|'.$field_name.'|%'];
            }
            $type = input('type', 0);
            if ($type) {
                $where[] = ['type', '=', $type];
            }
            $pk_id = input('pk_id', 0);
            if ($pk_id) {
                $where[] = ['pk_id', '=', $pk_id];
            }
            $where[] = ['id', 'in', array_column($res, 'id')];
            View::assign($this->service->getRelationsListPaginate($where, [], 'id asc'));
            $where_auto = [];
            $where_auto[] = ['name', 'in', array_column($res, 'table_name')];
            $table_auto_arr = (new TableAutoService())->getList($where_auto)->toArray();
            View::assign('auto', $table_auto_arr);
            try {
                $user_arr = AdminUser::where('user_id', 'in', array_column($res, 'user_id'))->select();
            } catch (\Exception $exception) {
                $user_arr = [];
            }
            View::assign('user_arr', $user_arr);
            return View::fetch();
        } else {
            $content = str_replace("delete_time", "delete_time_soft", $content);
            file_put_contents($file_name, $content);
            return redirect(url('detail', ['id'=>$id]), 0);
        }
    }



    /**
     * 详情
     */
    public function log()
    {
        $table_pk_id = input('table_pk_id', 0);
        $table_name = input('table_name', '');
        $log_id = $this->model::where([['pk_id', '=', $table_pk_id], ['table_name', '=', $table_name]])->value('id');
        $table_auto_id = TableAuto::where('name', $table_name)->value('id');
        $table_desc = TableAuto::where('name', $table_name)->value('desc');
        $base = new FileAutoLib('', $table_auto_id);
        $this_service = '\app\common\service\\' . $base->class_name . 'Service';
        $file_name = "../app/common/base/model/BaseModel.php";
        $content = file_get_contents($file_name);
        if (strpos($content, 'delete_time_soft') !== false) {
            $content = str_replace("delete_time_soft", "delete_time", $content);
            file_put_contents($file_name, $content);
            $data = (new $this_service())->getDeleteFullById($table_pk_id);
            if ($data) {
                $data = $data->toArray();
            }
            $where_relation = [];
            $where_relation[] = ['table_auto_id', '=', $table_auto_id];
            $where_relation[] = ['is_delete', '=', 1];
            $relations_arr = (new TableRelationsAutoService())->getRelationsList($where_relation)->toArray();
            $log_where = [];
            $log_where[] = [
                ['id' ,'=', $log_id],
                ['table_name', '=', $base->table_name]
            ];
            $tree_data = [];
            foreach ($relations_arr as $k=>$v) {
                $pids = $v['pids'];
                if ($pids) {
                    $route_arr = explode(',', trim($pids . ',' . $v['id'], ','));
                } else {
                    $route_arr = [$v['id']];
                }

                $ids = $this->getIds($data, $route_arr);
                $tree_data = array_merge($tree_data, $this->getTreeData($data, $route_arr));
                if ($ids) {
                    $log_where[] = [
                        ['pk_id', 'in', $ids],
                        ['table_name', '=', $v['bindTableAuto']['name']]
                    ];
                }
            }
            $tree_data[] = ["id"=>"root", "isroot"=>true, "topic"=>$table_desc . '_id:' . $table_pk_id];
            View::assign('tree_data', $tree_data);

            $res = [];
            foreach ($log_where as $v) {
                $data = $this->service->getRelationsList($v);
                if ($data) {
                    $data = $data->toArray();
                    $res = array_merge($res, $data);
                }
            }

            array_multisort(array_column($res, 'id'), SORT_ASC, $res);

            $data = input();
            $where = [];
            $start_time = input('start_time', '');
            $start_time = $start_time ? strtotime($start_time) : 0;
            $end_time = input('end_time', '');
            $end_time = $end_time ? strtotime($end_time) + 60 * 60 * 24 - 1 : time() + time();
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
            $table_name = input('table_name1', '');
            if ($table_name) {
                $where[] = ['table_name', '=', $table_name];
                $table_auto_id = TableAuto::where('name', $table_name)->value('id');
                $field_name_arr = (new TableFieldAutoService())->getList(['table_auto_id'=>$table_auto_id])->toArray();
                View::assign('field', $field_name_arr);
            } else {
                View::assign('field', []);
            }
            $user_id = input('user_id', 0, 'trim');
            if ($user_id) {
                $where[] = ['user_id', '=', $user_id];
            }
            $field_name = input('field_name', '');
            if ($field_name) {
                $where[] = ['field_name', 'like', '%|'.$field_name.'|%'];
            }
            $type = input('type', 0);
            if ($type) {
                $where[] = ['type', '=', $type];
            }
            $pk_id = input('pk_id', 0);
            if ($pk_id) {
                $where[] = ['pk_id', '=', $pk_id];
            }
            $where[] = ['pk_id', 'in', array_column($res, 'id')];
            $this->service->getRelationsListPaginate($where, [], 'id asc');
            View::assign($this->service->getRelationsListPaginate($where, [], 'id asc'));
            $where_auto = [];
            $where_auto[] = ['name', 'in', array_column($res, 'table_name')];
            $table_auto_arr = (new TableAutoService())->getList($where_auto)->toArray();
            View::assign('auto', $table_auto_arr);
            try {
                $user_arr = AdminUser::where('user_id', 'in', array_column($res, 'user_id'))->select();
            } catch (\Exception $exception) {
                $user_arr = [];
            }
            View::assign('user_arr', $user_arr);
            return View::fetch();
        } else {
            $content = str_replace("delete_time", "delete_time_soft", $content);
            file_put_contents($file_name, $content);
            return redirect($_SERVER["REQUEST_URI"], 0);
        }
    }


    /**
     * 获取数据对应层级id
     * @param $data
     * @param $route_arr
     * @return array
     */
    public function getIds($data, $route_arr)
    {
        $index = 0;
        $route_size = sizeof($route_arr);
        while ($index < $route_size) {
            $this_index = TableRelationsAuto::where('id', $route_arr[$index])->value('name');
            $res = [];
            if (!$index) {
                $res = $data[$this_index];
            }
            if ($index == 1) {
                foreach ($data as $v) {
                    $res[] = $v[$this_index];
                }
            }
            if ($index > 1) {
                foreach ($data as $v1) {
                    foreach ($v1 as $v) {
                        $res[] = $v[$this_index];
                    }
                }
            }

            $data = unserialize(serialize($res));
            $index ++;
        }
        if ($route_size == 1) {
            return array_column($data, 'id');
        } else {
            $res = [];
            foreach ($data as $v) {
                $ids = array_column($v, 'id');
                $res = array_merge($ids, $res);
            }
            return $res;
        }
    }


    /**
     * 获取数据对应层级id
     * @param $data
     * @param $route_arr
     * @return array
     */
    public function getTreeData($data, $route_arr)
    {
        $index = 0;
        $route_size = sizeof($route_arr);
        while ($index < $route_size) {
            $relation_data = (new TableRelationsAutoService())->getFullById($route_arr[$index]);
            $this_index = $relation_data['name'];
            $this_table_desc = $relation_data['bindTableAuto']['desc'];
            $res = [];
            if (!$index) {
                $res = $data[$this_index];
            }
            if ($index == 1) {
                foreach ($data as $v) {
                    $res[] = $v[$this_index];
                }
            }
            if ($index > 1) {
                foreach ($data as $v1) {
                    foreach ($v1 as $v) {
                        $res[] = $v[$this_index];
                    }
                }
            }

            $index ++;
            if ($index == $route_size) {
                $res = [];
                if ($index == 1) {
                    $this_data = $data[$this_index];
                    foreach ($this_data as $v1) {
                        $v1['parentid'] = 'root';
                        $v1['tree_id'] = $this_table_desc . '_id:' . $v1['id'];
                        $res[] = $v1;
                    }
                }
                if ($index == 2) {
                    $relation_data_last = (new TableRelationsAutoService())->getFullById($route_arr[$index-2]);
                    $relation_data_desc_last = $relation_data_last['bindTableAuto']['desc'];
                    foreach ($data as $v) {
                        $this_data = $v[$this_index];
                        foreach ($this_data as $v1) {
                            $v1['parentid'] = $relation_data_desc_last . '_id:' . $v['id'];
                            $v1['tree_id'] = $this_table_desc . '_id:' . $v1['id'];
                            $res[] = $v1;
                        }
                    }
                }

                if ($index == 3) {
                    $relation_data_last = (new TableRelationsAutoService())->getFullById($route_arr[$index-2]);
                    $relation_data_desc_last = $relation_data_last['bindTableAuto']['desc'];
                    foreach ($data as $v0) {
                        foreach ($v0 as $v) {
                            $this_data = $v[$this_index];
                            foreach ($this_data as $v1) {
                                $v1['parentid'] = $relation_data_desc_last . '_id:' . $v['id'];
                                $v1['tree_id'] = $this_table_desc . '_id:' . $v1['id'];
                                $res[] = $v1;
                            }
                        }
                    }
                }
            }
            $data = unserialize(serialize($res));
        }
        $return_data = [];
        foreach ($data as $v) {
            $v['pk_id'] = $v['id'];
            $v['id'] = $v['tree_id'];
            $v['topic'] = $v['tree_id'];
            $v['delete_time'] = $v['delete_time'] ? date('Y-m-d H:i:s', $v['delete_time']) : $v['delete_time'] ;
            $return_data[] = $v;
        }
//        if($route_size == 1){
//            foreach ($data as $v){
//                $v['pk_id'] = $v['id'];
//                $v['id'] = $v['tree_id'];
//                $v['topic'] = $v['tree_id'];
//                $v['delete_time'] = $v['delete_time'] ? date('Y-m-d H:i:s', $v['delete_time']) : $v['delete_time'] ;
//                $return_data[] = $v;
//            }
//        }else{
//            foreach ($data as $v1){
//                foreach ($v1 as $v){
//                    $v['pk_id'] = $v['id'];
//                    $v['id'] = $v['tree_id'];
//                    $v['topic'] = $v['tree_id'];
//                    $v['delete_time'] = $v['delete_time'] ? date('Y-m-d H:i:s', $v['delete_time']) : $v['delete_time'] ;
//                    $return_data[] = $v;
//                }
//
//            }
//        }



        return $return_data;
    }

    /**
     * 显示数据
     * @return string
     * @throws \Exception
     */
    public function showData()
    {
        $id = input('id', 0);
        $log_data = $this->service->getById($id);
        $table_auto_id = TableAuto::where('name', $log_data['table_name'])->value('id');
        $data = json_decode($log_data['data'], true);
        $field_desc = [];
        foreach ($data as $k=>$v) {
            $where = [];
            $where[] = ['field_name', '=', $k];
            $where[] = ['table_auto_id', '=', $table_auto_id];
            try {
                $field_desc[$k] = TableFieldAuto::where($where)->value('field_desc');
            } catch (\Exception $e) {
                $field_desc[$k] = '';
            }
        }
        View::assign('data', $data);
        View::assign('field_desc', $field_desc);
        return View::fetch();
    }

    /**
     * 根据表名获取字段
     */
    public function getFieldName()
    {
        $table_name = input('table_name', '');
        $table_auto_id = TableAuto::where('name', $table_name)->value('id');
        $field_name_arr = (new TableFieldAutoService())->getList(['table_auto_id'=>$table_auto_id])->toArray();
        return success($field_name_arr);
    }
}
